/*
 * @Author: muuzi@163.com muuzi@163.com
 * @Date: 2024-06-06 11:00:22
 * @LastEditors: muuzi@163.com muuzi@163.com
 * @LastEditTime: 2024-12-15 23:07:39
 * @FilePath: /my-vue3-project/src/store/modules/user.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { to } from "await-to-js";
import { getToken, removeToken, setToken } from "@/utils/auth";
import {
  login as loginApi,
  logout as logoutApi,
} from "@/api/login";
import {
  getUserInfo,
} from "@/api/user";
import type { LoginData } from "@/api/types";
import defAva from "@/assets/images/profile.jpg";


export const useUserStore = defineStore("user", () => {
  const token = ref(getToken());
  const name = ref("");
  const nickname = ref("");
  const userId = ref<string | number>("");
  const avatar = ref("");
  const roles = ref<Array<string>>([]); // 用户角色编码集合 → 判断路由权限

  /**
   * 登录
   * @param userInfo
   * @returns
   */
  const login = async (userInfo: LoginData): Promise<void> => {
    const [err, res] = await to(loginApi(userInfo));
    if (res) {
      const data = res.data;
      setToken(data.token);
      token.value = data.token;
      uni.showToast({
        icon: "none",
        title: "登录成功",
      });
      // 跳转
      return Promise.resolve();
    }
    uni.showToast({
      icon: "error",
      title: err.msg||"登录失败",
    });
    return Promise.reject(err);
  };

  // 获取用户信息
  const getInfo = async (): Promise<void> => {
    const [err, res] = await to(getUserInfo());
    console.log('getinfo',err, res)
    if (res) {
      const data = res.data;
      const profile =
      data.avatar == "" || data.avatar == null ? defAva : data.avatar;

      if (data.roles && data.roles.length > 0) {
        // 验证返回的roles是否是一个非空数组
        roles.value = data.roles;
      } else {
        roles.value = ["ROLE_DEFAULT"];
      }
      name.value = data.username;
      avatar.value = profile;
      userId.value = data.userId;
      nickname.value = data.nickname;
      return Promise.resolve();
    }
    return Promise.reject(err);
  };

  // 注销
  const logout = async (): Promise<void> => {
    await logoutApi();
    token.value = "";
    roles.value = [];
    removeToken();
  };

  const setAvatar = (value: string) => {
    avatar.value = value;
  };
  return {
    userId,
    token,
    nickname,
    avatar,
    roles,
    login,
    getInfo,
    logout,
    setAvatar,
  };
});
export default useUserStore;
